package nc.ui.mmpac.sumpickm.handler.body;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import nc.bs.framework.common.NCLocator;
import nc.bs.trade.business.HYPubBO;
import nc.itf.bd.material.baseinfo.IMaterialBaseInfoQueryService;
import nc.ui.ml.NCLangRes;
import nc.ui.mmf.framework.handler.MMBaseHandler;
import nc.ui.mmf.framework.handler.MMEventHandler;
import nc.ui.mmpac.sumpickm.util.SumPickmActionUtil;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.bill.BillItem;
import nc.ui.pubapp.uif2app.event.IAppEventHandler;
import nc.ui.pubapp.uif2app.event.card.CardBodyAfterEditEvent;
import nc.ui.trade.business.HYPubBO_Client;
import nc.uif.pub.exception.UifException;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.bc.pmpub.project.ProjectHeadVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.stordoc.StordocVO;
import nc.vo.mmpac.sumpickm.consts.SumPickmConst;
import nc.vo.mmpac.sumpickm.entity.AggSumPickmVO;
import nc.vo.mmpac.sumpickm.entity.SumPickmSumVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import nc.vo.pubapp.pattern.model.entity.bill.IBill;

public class SumPickmCardBodySumAfterEditHandler extends MMEventHandler
		implements IAppEventHandler<CardBodyAfterEditEvent> {

	@Override
	public void handleAppEvent(CardBodyAfterEditEvent e) {
		if ("nsplanoutastnum".equals(e.getKey())) {
			IMaterialBaseInfoQueryService service = NCLocator.getInstance()
					.lookup(IMaterialBaseInfoQueryService.class);
			Double changeValue = Double.valueOf(e.getValue().toString());
			String cmaterialid = e.getBillCardPanel()
					.getBodyValueAt(e.getRow(), "cmaterialvid").toString();
			Object project = e.getBillCardPanel().getBodyValueAt(e.getRow(),
					"cprojectid");
			String cproectid = project == null ? "" : project.toString();
			String project_name = this.getProjectNameByPK(cproectid);
			Object coutstockid = e.getBillCardPanel().getBodyValueAt(
					e.getRow(), "coutstockid");
			String pk_coutstock = coutstockid == null ? "" : coutstockid
					.toString();
			String stockCode = this.getStockCodeByPK(pk_coutstock);
			double changerate = 0;
			String[] pks = { cmaterialid };

			MaterialVO[] mVOs = null;
			try {
				mVOs = service.queryDataByPks(pks);
			} catch (BusinessException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (mVOs != null) {
				nc.vo.bd.material.MaterialConvertVO[] convert = mVOs[0]
						.getMaterialconvert();
				if (convert != null) {
					String changerate1 = convert[0].getMeasrate();
					String[] hsl = changerate1.split("/");
					Double hsl1 = Double.valueOf(hsl[0].trim());
					Double hsl2 = Double.valueOf(hsl[1].trim());
					changerate = new BigDecimal(hsl1 / hsl2).setScale(6,
							BigDecimal.ROUND_HALF_UP).doubleValue();
				}
			}
			int length = e.getBillCardPanel()
					.getBillModel(SumPickmConst.TAB_BODY).getRowCount();
			// BillItem[] items
			// =e.getBillCardPanel().getBillModel(SumPickmConst.TAB_BODY).getBodyItems();
			// int length = items.length;
			Map<Integer, String> tempMap = new HashMap<Integer, String>();
			for (int i = 0; i < length; i++) {

				String pk_material = e.getBillCardPanel()
						.getBillModel(SumPickmConst.TAB_BODY)
						.getValueAt(i, "cbmaterialid").toString();
				Object bodyProject = e.getBillCardPanel()
						.getBillModel(SumPickmConst.TAB_BODY)
						.getValueAt(i, "cbprojectid");
				String cbprojectid = bodyProject == null ? "" : bodyProject
						.toString();
				Object bodystockid = e.getBillCardPanel()
						.getBillModel(SumPickmConst.TAB_BODY)
						.getValueAt(i, "coutstockid");
				String pk_bodystock = bodystockid == null ? "" : bodystockid
						.toString();
				if (pk_material.equals(cmaterialid)
						&& (cbprojectid.equals(cproectid) || cbprojectid
								.equals(project_name))
						&& (pk_bodystock.equals(stockCode)||pk_bodystock.equals(pk_coutstock))) {
					String nplanoutastnum = e.getBillCardPanel()
							.getBillModel(SumPickmConst.TAB_BODY)
							.getValueAt(i, "nplanoutastnum").toString();
					tempMap.put(i, nplanoutastnum);
				}
			}
			Set<Integer> set = tempMap.keySet();
			double totalSum = 0;
			for (Integer in : set) {
				Double tempStr = Double.valueOf(tempMap.get(in));
				totalSum = totalSum + tempStr;

			}

			if (set.size() == 0) {
				return;
			}
			for (Integer in : set) {
				Double oldValue = Double.valueOf(tempMap.get(in));
				Double percent = new BigDecimal(oldValue / totalSum).setScale(
						6, BigDecimal.ROUND_HALF_UP).doubleValue();
				Double newItemValue = new BigDecimal(changeValue * percent)
						.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
				tempMap.put(in, String.valueOf(newItemValue));

			}
			double tempSum = 0;
			for (Integer in : set) {
				Double oldValue = Double.valueOf(tempMap.get(in));
				tempSum = tempSum + oldValue;

			}
			double diffValue = tempSum - changeValue;
			List<Integer> list = new ArrayList<Integer>(set);
			int first = list.get(0);
			Double lastDiffValue = Double.valueOf(tempMap.get(first))
					- diffValue;
			tempMap.put(
					first,
					String.valueOf(Double.valueOf(tempMap.get(first))
							- diffValue));

			for (Integer in : set) {
				String lastValue = tempMap.get(in);
				Double temp = Double.valueOf(lastValue) * changerate;
				Double mainNum = new BigDecimal(temp).setScale(6,
						BigDecimal.ROUND_HALF_UP).doubleValue();
				e.getBillCardPanel().getBillModel(SumPickmConst.TAB_BODY)
						.setValueAt(lastValue, in, "nplanoutastnum");
				e.getBillCardPanel().getBillModel(SumPickmConst.TAB_BODY)
						.setValueAt(mainNum, in, "nplanoutnum");
				e.getBillCardPanel().getBillModel(SumPickmConst.TAB_BODY)
						.setValueAt(lastValue, in, "nbcckastnum");
				e.getBillCardPanel().getBillModel(SumPickmConst.TAB_BODY)
						.setValueAt(mainNum, in, "nbccknum");
			}

		}
		MMBaseHandler handler = this.getHandler(e.getKey());
		if (!MMValueCheck.isEmpty(handler)) {
			handler.afterEdit(e);
		}
	}

	@Override
	public void initMap() {
		this.putHandler(SumPickmSumVO.CDELIVERORGVID,
				SumPickmCardBodySumCdeliverorgvidHandler.class);
		this.putHandler(SumPickmSumVO.CDELIVERORGID,
				SumPickmCardBodySumCdeliverorgvidHandler.class);
		this.putHandler(SumPickmSumVO.COUTSTOCKID,
				SumPickmCardBodySumCoutstockidHandler.class);
		this.putHandler(SumPickmSumVO.VSSTOCKBATCHCODE,
				SumPickmCardBodySumVbatchcodeHandler.class);
	}

	public static String getProjectNameByPK(String pk_project) {
		String project_name = null;
		// HYPubBO hy = new HYPubBO();

		if (pk_project == null || "".equals(pk_project)) {
			return "";
		}
		String condition = "pk_project = '" + pk_project + "' and dr =0";
		ProjectHeadVO[] pVOs = null;
		try {
			pVOs = (ProjectHeadVO[]) HYPubBO_Client.queryByCondition(
					ProjectHeadVO.class, condition);
		} catch (UifException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (pVOs.length != 0) {
			project_name = pVOs[0].getProject_name();
		}
		return project_name;

	}
	
	public String getStockCodeByPK(String pk_stordoc){
		//String code = null;
		StordocVO stock = null;
		if (pk_stordoc == null || "".equals(pk_stordoc)) {
			return "";
		}
		try {
			SuperVO svo =HYPubBO_Client.queryByPrimaryKey(StordocVO.class, pk_stordoc);
			if(svo != null){
				stock = (StordocVO) svo;
			}
		} catch (UifException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stock.getCode();
	}

}
